<!--数据生成页面-->
<template>
  <div style="height: calc(100vh - 200px); overflow: auto">
    <el-form>
      <el-row :gutter="20" class="statistic">
        <el-col :span="6">
          <el-form-item label="需要生成数量">
            <el-input v-model="incompleteNum"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <div>
            <el-button class="enlarge-button" icon="el-icon-video-play" round @click="startGeneration">开始生成
            </el-button>
          </div>
        </el-col>
        <el-col :span="6">
          <el-form-item label="成功生成数量">
            <el-input v-model="completedNum"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-card class="box-main" shadow="never">
      <div slot="header" class="clearfix">
        <span>全局变量</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="addGlobalData">添加全局变量</el-button>
      </div>
      <el-table :data="globalTableData" style="width: 100%">
        <el-table-column prop="globalKey" label="生成标识" width="200" align="center">
          <template v-slot="scope">
            <span>{{ scope.row.globalKey }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="genType" label="全局变量生成" width="680" align="center">
          <template v-slot="scope">
            <el-select v-model="scope.row.genType" placeholder="请选择">
              <el-option
                  v-for="item in globalGenTypeOptions"
                  :key="item.type"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
            <span style="margin-right: 20px;"></span>
            <el-select v-model="scope.row.genKeyCode" placeholder="请选择" v-if="scope.row.genType=='primary'"  style="width: 240px">
              <el-option
                  v-for="item in primaryOptions"
                  :key="item.type"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
            <el-input
                style="width: 240px"
                placeholder="表名.字段名"
                v-if="scope.row.genType=='table'"
                v-model="scope.row.genKeyTable"/>
          </template>
        </el-table-column>
        <el-table-column prop="check" label="数据预览" width="480" align="center">
          <template v-slot="scope">
            <span>{{ scope.row }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="check" label="操作" width="480" align="center">
          <template v-slot="scope">
            <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                @click="removeGlobalData(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-collapse v-model="activeNames" @change="handleChange" class="box-main">
      <el-collapse-item :title="'表名：'+tableData[0].tableName" v-for="(tableData,index) in tableDataArray"
                        :key="index"
                        :name="index">

        <el-card>
          <div slot="header" class="clearfix">
            <span>{{ '表名：' + tableData[0].tableName }}</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="removeTableData(index)">移除此表
            </el-button>
          </div>
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="columnName" label="字段名" width="180" align="center"/>
            <el-table-column prop="columnComment" label="字段注释" width="240" align="center"/>
            <el-table-column prop="genType" label="数据生成" width="680" align="center">
              <template v-slot="scope">
                <el-select v-model="scope.row.genType" placeholder="请选择">
                  <el-option
                      v-for="item in genTypeOptions"
                      :key="item.type"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
                <span style="margin-right: 20px;"></span>
                <el-select v-model="scope.row.genKeyGlobal" placeholder="请选择" v-if="scope.row.genType=='global'"  style="width: 240px">
                  <el-option
                      v-for="item in globalOptions"
                      :key="item.type"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
                <el-cascader
                    style="width: 240px"
                    placeholder="输入搜索"
                    v-model="scope.row.genKeyCode"
                    :options="genKeyOptions"
                    v-if="scope.row.genType=='code'"
                    filterable
                    @change="handleGenKeyChange"/>
                <el-input
                    style="width: 240px"
                    placeholder="表名.字段名"
                    v-if="scope.row.genType=='table'"
                    v-model="scope.row.genKeyTable"/>
              </template>
            </el-table-column>
            <el-table-column prop="dataType" label="数据类型" width="180" align="center"/>
            <el-table-column prop="isNullable" label="是否为空" width="140" align="center"/>
            <el-table-column prop="lengthType" label="长度类型" width="140" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.lengthType==='num'">数字</span>
                <span v-else-if="scope.row.lengthType==='char'">字符</span>
                <span v-else>其他</span>
              </template>
            </el-table-column>
            <el-table-column prop="length" label="长度" width="140" align="center"/>
            <el-table-column prop="check" label="数据预览" width="480" align="center">
              <template v-slot="scope">
                <span>{{ scope.row }}</span>
              </template>
            </el-table-column>

          </el-table>
        </el-card>


      </el-collapse-item>
    </el-collapse>


  </div>
</template>

<script>
import {listField} from "@/api/data-generate/TableTree";
import {queryConfiguration, saveConfiguration, startGeneration} from "@/api/data-generate/DataGenerate";

export default {
  name: "DataGenerate",
  props: {
    tableInfo: Object,
    connectionItem: Object,
    transTableDataArray: Function
  },
  watch: {
    //监听tableInfo是否发生变化
    tableInfo: function () {
      //查询表字段列表
      this.listField()
    }
  },
  mounted() {
    const that = this
    //监控生成配置数据变化触发保存
    this.$watch('configurationData', (newVal, oldVal) => {
      that.saveConfiguration()
    }, {deep: true});

    //监控全局变量表格的变化，更新全局变量选择器的数据
    this.$watch('globalTableData', (newVal, oldVal) => {
      //先清空全局变量选择器
      this.globalOptions = []
      //将全局变量表格的数据更新到全局变量选择器中
      this.globalTableData.forEach(ele => {
        let globalKey = ele.globalKey;
        this.globalOptions.push({
          value: globalKey,
          label: '生成标识：' + globalKey
        })
      })

    }, {deep: true});


  },
  created() {
    const that = this;
    let params = {
      connectionId: this.connectionItem.connectionId
    };
    queryConfiguration(params).then(res => {
      if (res.code === 200) {
        let data = res.data;
        that.activeNames = data.activeNames === null ? [] : data.activeNames;
        that.globalTableData = data.globalTableData === null ? [] : data.globalTableData;
        that.tableDataArray = data.tableDataArray === null ? [] : data.tableDataArray;
      } else {
        that.openLayer('消息', res.msg, 'error');
      }
    });
  },
  computed: {
    //生成配置数据
    configurationData() {
      const {globalTableData, activeNames, tableDataArray} = this;
      return {
        globalTableData,
        activeNames,
        tableDataArray
      };
    }
  },
  data() {
    return {
      //需要生成的数量
      incompleteNum: 100,
      //成功生成的数量
      completedNum: 0,
      //全局变量表格
      globalTableData: [],
      //全局变量生成类型选择器
      globalGenTypeOptions: [{
        value: 'primary',
        label: '全局主键'
      }, {
        value: 'table',
        label: '自定义表'
      }],
      //全局变量全局主键选择器
      primaryOptions: [
        {
          value: 'increase',
          label: '自增序列'
        },
        {
          value: 'uuid',
          label: 'UUID'
        }
      ],
      //全局变量其他类型选择器
      otherOptions: [],


      //全局变量选择器
      globalOptions: [],
      //折叠框激活面板
      activeNames: [],
      //待生成的表结构数组
      tableDataArray: [],
      //生成类型选择器
      genTypeOptions: [{
        value: 'global',
        label: '全局变量'
      }, {
        value: 'code',
        label: '通用数据'
      }, {
        value: 'table',
        label: '自定义表'
      }],

      //通用类型选择器
      genKeyOptions: [
        {
          value: 'common',
          label: '通用',
          children: [
            {
              value: 'primary',
              label: '主键',
              children: [
                {
                  value: 'increase',
                  label: '自增序列'
                },
                {
                  value: 'uuid',
                  label: 'UUID'
                }
              ]
            },
            {
              value: 'datetime',
              label: '日期时间',
              children: [
                {
                  value: 'thisYearDatetime',
                  label: '今年的日期时间（YYYY-MM-DD HH:MM:SS）'
                },
                {
                  value: 'lastYearDatetime',
                  label: '去年的日期时间（YYYY-MM-DD HH:MM:SS）'
                },
                {
                  value: 'thisYearDate',
                  label: '今年的日期（YYYY-MM-DD）'
                },
                {
                  value: 'lastYearDate',
                  label: '去年的日期（YYYY-MM-DD）'
                },
                {
                  value: 'time',
                  label: '时间（HH:MM:SS）'
                }
              ]
            }
          ]
        },
        {
          value: 'zh',
          label: '中文',
          children: [
            {
              value: 'name',
              label: '姓名',
              children: [
                {
                  value: 'fullName',
                  label: '全名'
                },
                {
                  value: 'firstName',
                  label: '姓氏'
                },
                {
                  value: 'lastName',
                  label: '名字'
                }
              ]
            },
            {
              value: 'address',
              label: '地址',
              children: [
                {
                  value: 'fullAddress',
                  label: '全地址'
                }
              ]
            }
          ]
        },
        {
          value: 'en',
          label: '英文',
          children: []
        }
      ],

    }
  },
  methods: {
    //查询表字段列表
    listField() {
      if (this.connectionItem !== undefined && this.connectionItem !== null) {
        const connectionId = this.connectionItem.connectionId;
        const tableName = this.tableInfo.tableName;
        const param = {connectionId: connectionId, tableName: tableName}
        listField(param).then(res => {
          //将表字段列表添加到表结构数组
          this.tableDataArray.push(res.data)
          this.$message.success("选择的表添加成功");
        })
      }
    },
    //添加全局变量
    addGlobalData() {
      var globalKey = 1;
      if (this.globalTableData.length > 0) {
        globalKey = this.globalTableData[this.globalTableData.length - 1].globalKey;
        globalKey += 1;
      }
      let row = {
        globalKey: globalKey,
        genType: 'primary',
        genKeyCode: 'increase'
      };
      this.globalTableData.push(row);
    },
    //删除全局变量
    removeGlobalData(row) {
      let filter = this.globalTableData.filter(item => item.globalKey !== row.globalKey);
      this.globalTableData = filter;
    },

    //折叠面板激活
    handleChange(val) {
      //激活的面板编号
      // console.log(val);
    },
    //选择通用数据级联选择器
    handleGenKeyChange(value) {
      // console.log(value);
    },
    //移除此表
    removeTableData(index) {
      this.tableDataArray.splice(index, 1)
    },
    //开始数据生成
    startGeneration() {
      const that = this
      let param = {
        connectionId: this.connectionItem.connectionId,
        generationNum: this.incompleteNum,
        globalTableData: this.globalTableData,
        tableDataList: this.tableDataArray,
      }
      startGeneration(param).then(res => {
        if (res.code === 200) {
          console.log('开始数据生成')
        }
      })

    },

    //保存生成配置
    saveConfiguration() {
      if (this.connectionItem.connectionId !== undefined && this.connectionItem.connectionId != null) {
        let param = {
          connectionId: this.connectionItem.connectionId,
          globalTableData: this.globalTableData,
          activeNames: this.activeNames,
          tableDataArray: this.tableDataArray
        }
        saveConfiguration(param).then(res => {
          if (res.code === 200) {
            //将待生成的表结构数组传递给父组件
            this.transTableDataArray(this.tableDataArray)
            console.log('保存成功')
          }
        })
      }
    },
  }
}

</script>


<style>
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.statistic {
  margin-top: 2%;
  width: 90%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box-main {
  margin-top: 2%;
  margin-left: 5%;
  width: 90%;
}

.enlarge-button {
  width: 120px;
  height: 60px;
}
</style>